'use strict';

const RouterService = require('../base');
const { Op } = require('sequelize');

class BannerService extends RouterService {
    static get modelName() {
        return 'Business.Cart';
    }
      getPageInclude() {
          return [
              {
                  model: this.ctx.model.Business.Product,
                  as: 'product',
              }
          ]
      }

    async create(data) {
      // 创建购物车，检查是否存在，存在就更新数量，不存在就创建
      let { user_id, count = 1, product_id } = data;
      if (!user_id) {
          throw new Error('请登录');
      }
      const cart = await this.ctx.model.Business.Cart.findOne({
          where: {
              user_id,
              product_id
          }
      });
      if (cart) {
          return await this.ctx.model.Business.Cart.update({
              count: cart.count + count
          }, {
              where: {
                  id: cart.id
              }
          });
      } else {
          return await this.ctx.model.Business.Cart.create({
              ...data
          });
      }
  }

  async batchDelete(ids) {
      return await this.ctx.model.Business.Cart.destroy({
          where: {
              id: ids
          }
      });
  }
  async updateCartStatusAll(data) {
      if (!data.user_id) {
          throw new Error('请登录');
      }
      // 所有的都变成checked = 0
      await this.ctx.model.Business.Cart.update({
          status: 0
      }, {
          where: {
              user_id: data.user_id
          }
      })
      return await this.ctx.model.Business.Cart.update({
          status: 1
      }, {
          where: {
              user_id: data.user_id,
              id: {
                  [Op.in]: data.checkedId || []
              }
          }
      });
  }
}

module.exports = BannerService;
